package com.gitee.loyo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.loyo.Result;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class ChargeResponseBodyAdvice implements ResponseBodyAdvice {
    final ChargeNotifyProperties chargeNotifyProperties;
    final ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getParameterType() == Result.class;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Result result = (Result) body;
        Result result2 = null;
        try {
            log.info("原来的 {}", objectMapper.writeValueAsString(result));
            result2=  result.encryptAndSign(
                chargeNotifyProperties.getOperatorId(),
                chargeNotifyProperties.getDataSecretIV(),
                chargeNotifyProperties.getDataSecret(),
                chargeNotifyProperties.getSigSecret(),
                o -> result.getData() == null ?
                    null : result.getData() instanceof String ?
                    (String) result.getData() : objectMapper.writeValueAsString(result.getData())
            );
            return result2;
        }finally {
            log.info("现在的 {}", objectMapper.writeValueAsString(result2));
        }
    }
}
